<template>
  <div class="j-input-wrapper" ref="jInputWrapper">
    <slot> </slot>
  </div>
</template>
<script>
export default {
  name: 'JInputWrapper',
  mounted() {
    let elInput = this.$refs.jInputWrapper.children[0]
    let input = elInput.children[0]
    input.required = true

    let label = document.createElement('label')
    label.innerText = input.placeholder
    input.placeholder = ''

    let underline = document.createElement('div')
    underline.classList.add('underline')

    elInput.appendChild(label)
    elInput.appendChild(underline)

    if (input.type == 'password' && !input.readOnly) {
      input.readOnly = true

      setTimeout(() => {
        input.readOnly = false
      }, 300)
    }
  },
}
</script>
<style lang="scss">
.j-input-wrapper {
  position: relative;
  width: 100%;
  height: 40px;
  margin-top: 20px;

  input {
    width: 100%;
    border: none;
    font-size: 16px;
    border-bottom: 2px solid #808080;
    background-color: transparent;
  }

  label {
    position: absolute;

    left: 12px;
    font-size: 16px;
    color: #808080;
    /* 点击lable，穿透输入框 */
    pointer-events: none;
    transition: all 0.3s ease;
  }

  .underline {
    position: absolute;
    left: 0;
    bottom: 0;
    height: 10px;
    width: 100%;
    border-bottom: 2px solid #2c6fdb;
    border-radius: 5px;
    transform: scaleX(0);
    transition: all 0.3s ease;
  }

  /* 输入框获取焦点或输入有效值时 */
  input:focus ~ label,
  input:valid ~ label {
    // lable上移，同时改变字号和颜色
    transform: translateY(-26px);
    font-size: 14px;
    color: #2c6fdb;
  }

  input:focus ~ .underline,
  input:valid ~ .underline {
    transform: scaleX(1);
  }
}
</style>
